package com.yxq.mdt.app.modules.market.ui;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.IntentHelper;
import com.yxq.mdt.app.base.BaseFragment;
import com.yxq.mdt.app.constant.RouteTable;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.modules.login.bean.UserBean;
import com.yxq.mdt.app.modules.main.bean.NameAndPhoneBean;
import com.yxq.mdt.app.modules.market.bean.MallPMBean;
import com.yxq.mdt.app.modules.message.ui.MessageTabActivity;
import com.yxq.mdt.app.modules.market.bean.MallBannerBean;
import com.yxq.mdt.app.modules.market.bean.MallClassGoodsBean;
import com.yxq.mdt.app.modules.market.bean.MallGoodsBean;
import com.yxq.mdt.app.modules.market.bean.MallGridListBean;
import com.yxq.mdt.app.modules.market.bean.MallListBean;
import com.yxq.mdt.app.modules.market.bean.MallNoticeBean;
import com.yxq.mdt.app.modules.market.bean.MallPanicBuyingBean;
import com.yxq.mdt.app.modules.market.bean.MallRecommendBean;
import com.yxq.mdt.app.modules.market.bean.MallResponseBean;
import com.yxq.mdt.app.modules.market.model.MarketModel;
import com.yxq.mdt.app.modules.market.presenter.IMainMarketContract;
import com.yxq.mdt.app.modules.market.presenter.MainMarketPresenter;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.shoppingcart.ui.CartActivity;
import com.yxq.mdt.app.modules.splash.model.SplashModel;
import com.yxq.mdt.app.net.ApiModel;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @描述 商城主页
 * @作者 L
 * @创建日期 2019/9/19 0019 11:03
 */
public class MainMarketFragment extends BaseFragment<MainMarketPresenter> implements IMainMarketContract.View {

    @BindView(R.id.home_iv_cart)
    ImageView homeIvCart;
    private AppCompatImageView mMallBackImage;
    private RecyclerView mRecyclerView;
    private MainMallListAdapter mAdapter;
    private boolean mCanBack = false;
    private List<MallListBean> mMallListBeanList;
    private RefreshLayout mRefreshLayout;
    @BindView(R.id.market_tv_search)
    TextView mSearchView;

    /**
     * 设置是否有返回按钮
     *
     * @param canBack
     */
    public void setCanBack(boolean canBack) {
        this.mCanBack = canBack;
    }


    @Override
    protected int attachLayoutId() {
//        setStatusBarColor(R.color.colorPrimary);
        return R.layout.fragment_main_mall_layout;
    }


    @Override
    public void initView(View view) {
        mRefreshLayout = view.findViewById(R.id.refreshLayout);
        mRefreshLayout.setOnRefreshListener(refreshLayout -> {
            if (mPresenter != null) {
                mAdapter.clear();
                mPresenter.getMainMarketList();
            }
        });
        mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            mPresenter.getMainMarketGoodsMoreList();
        });
        //跳转至搜索页
        mSearchView.setOnClickListener(view12 -> IntentHelper.arouter(RouteTable.ROUTER_ACTIVITY_SEARCH));
        mMallBackImage = view.findViewById(R.id.mMallBackImage);
        mMallBackImage.setVisibility(mCanBack ? View.VISIBLE : View.GONE);
        mMallBackImage.setOnClickListener(view1 -> onViewClicked(mMallBackImage));
        mRecyclerView = view.findViewById(R.id.rcv_recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mMallListBeanList = new ArrayList<>();
        mAdapter = new MainMallListAdapter(mMallListBeanList);
        mAdapter.setMainMallInterface(time -> {
            //秒杀倒计时结束
            mRefreshLayout.autoRefresh();
        });
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setEmptyView(R.layout.layout_empty_network_error_view, mRecyclerView);
        mAdapter.isUseEmpty(false);
        mAdapter.getEmptyView().findViewById(R.id.empty_btn_go_connect_network).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRefreshLayout.autoRefresh();
            }
        });
        List<String> keys = getHisSearchTags();
        //初始化搜索框默认值，目前逻辑是搜索记录的第一条
        mSearchView.setText((keys != null && keys.size() > 0) ? keys.get(keys.size() - 1) : "搜索一下");
    }

    @Override
    public void initData() {
        loadCache();
        mPresenter.getPersonalMyData();
        mRefreshLayout.autoRefresh();
        SplashModel.getNameAndPhone(new ApiModel.CommonCallback<NameAndPhoneBean>() {
            @Override
            public void onSuccess(NameAndPhoneBean nameAndPhoneBean) {
                if (nameAndPhoneBean != null) {
                    Hawk.delete(SPKey.SP_KEY_NAME_PHONE_INFO);
                    Hawk.put(SPKey.SP_KEY_NAME_PHONE_INFO, nameAndPhoneBean);
                }
            }

            @Override
            public void onError(String errMsg) {
                showCenterToast(errMsg);
            }
        });
    }

    /**
     * 滑动页面至顶部并刷新数据
     */
    public void refresh() {
        if (mAdapter != null && mAdapter.getData() != null && mAdapter.getData().size() > 0) {
            mRecyclerView.scrollToPosition(0);
        }
        SplashModel.getNameAndPhone(new ApiModel.CommonCallback<NameAndPhoneBean>() {
            @Override
            public void onSuccess(NameAndPhoneBean nameAndPhoneBean) {
                if (nameAndPhoneBean != null) {
                    Hawk.delete(SPKey.SP_KEY_NAME_PHONE_INFO);
                    Hawk.put(SPKey.SP_KEY_NAME_PHONE_INFO, nameAndPhoneBean);
                }
            }

            @Override
            public void onError(String errMsg) {
                showCenterToast(errMsg);
            }
        });
        mRefreshLayout.autoRefresh();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    /**
     * 预加载缓存数据
     */
    private void loadCache() {
        String mallResponseBean = Hawk.get("market", null);
        if (mallResponseBean != null) {
            initMarketIndexData(JSON.parseObject(mallResponseBean, MallResponseBean.class));
        }
    }

    @Override
    public MainMarketPresenter getPresenter() {
        return new MainMarketPresenter(this, new MarketModel());
    }

    @Override
    public void onLoadSuccess(MallResponseBean mallResponseBean) {
        mRefreshLayout.finishRefresh();
        if (mallResponseBean == null) {
            return;
        }
        Hawk.put("market", JSON.toJSONString(mallResponseBean));
        initMarketIndexData(mallResponseBean);
    }

    /**
     * 设置商城首页顶部除分页商品数据
     *
     * @param mallResponseBean
     */
    private void initMarketIndexData(MallResponseBean mallResponseBean) {
        mMallListBeanList.clear();
        List<MallResponseBean.ModuleListBean> moduleListBeanList = mallResponseBean.getModule_list();
        List<MallResponseBean.BlockListBean> blockListBeanList = mallResponseBean.getBlock_list();
        for (MallResponseBean.ModuleListBean moduleBean : moduleListBeanList) {

            switch (moduleBean.getName()) {
                case "banner"://广告
                    MallBannerBean mallBannerBean = new MallBannerBean();
                    mallBannerBean.setBannerListBean(mallResponseBean.getBanner_list());
                    mMallListBeanList.add(mallBannerBean);
                    break;
                case "nav"://导航菜单
                    MallGridListBean mallGridListBean = new MallGridListBean();
                    mallGridListBean.setNavIconListBeanList(mallResponseBean.getNav_icon_list());
                    mMallListBeanList.add(mallGridListBean);
                    break;
                case "notice"://通知
                    MallNoticeBean mallNoticeBean = new MallNoticeBean();
                    mallNoticeBean.setNotice(mallResponseBean.getNotice());
                    mMallListBeanList.add(mallNoticeBean);
                    //添加礼包入口
                    NameAndPhoneBean nameAndPhoneBean = Hawk.get(SPKey.SP_KEY_NAME_PHONE_INFO);
                    //判断礼包是否显示
                    if (nameAndPhoneBean != null && nameAndPhoneBean.getPmSetting() != null && nameAndPhoneBean.getPmSetting().getIs_show() == 1) {
                        MallPMBean mallPMBean = new MallPMBean();
                        mallPMBean.setId(nameAndPhoneBean.getPmSetting().getGift_goods_id());
                        mallPMBean.setUrl(nameAndPhoneBean.getPmSetting().getPm_url());
                        mallPMBean.setGrift_img_url(nameAndPhoneBean.getPmSetting().getGrift_img_url());
                        if (nameAndPhoneBean.getSmallBag() != null) {
                            mallPMBean.setSmall_gift_img_url(nameAndPhoneBean.getSmallBag().getGrift_img_url());
                            mallPMBean.setSmall_gift_goods_id(nameAndPhoneBean.getSmallBag().getGift_goods_id());
                        }
                        mallPMBean.setPm_img_url(nameAndPhoneBean.getPmSetting().getPm_img_url());
                        mMallListBeanList.add(mallPMBean);
                    }
                    break;
                case "miaosha"://秒杀
                    //判断是否有秒杀
                    if (mallResponseBean.getMiaosha().getRest_time() != 0 && mallResponseBean.getMiaosha().getGoods_list() != null) {
                        MallPanicBuyingBean mallPanicBuyingBean = new MallPanicBuyingBean();
                        mallPanicBuyingBean.setMiaoshaBean(mallResponseBean.getMiaosha());
                        mMallListBeanList.add(mallPanicBuyingBean);
                    }
                    break;
                case "block"://推荐商品
                    for (MallResponseBean.BlockListBean blockListBean : blockListBeanList) {
                        if (blockListBean.getId().equals(moduleBean.getBlock_id())) {
                            MallRecommendBean mallRecommendBean = new MallRecommendBean();
                            mallRecommendBean.setBlockListBean(blockListBean);
                            mMallListBeanList.add(mallRecommendBean);
                            break;
                        }
                    }
                    break;
                case "cat"://分类商品
                    int cols = mallResponseBean.getCat_goods_cols();
                    for (MallResponseBean.CatListBean catListBean : mallResponseBean.getCat_list()) {
                        if ("1".equals(catListBean.getIs_show())) {
                            //判断等于1才显示
                            MallClassGoodsBean mallClassGoodsBean = new MallClassGoodsBean();
                            mallClassGoodsBean.setCols(cols);
                            mallClassGoodsBean.setCatListBean(catListBean);
                            mMallListBeanList.add(mallClassGoodsBean);
                        }
                    }
                    break;
            }
        }
        mAdapter.notifyDataSetChanged();
        //是否显示缺省页
        mAdapter.isUseEmpty(!(mAdapter.getData().size() > 0));
        if (mPresenter != null) {
            //分页查询商品数据
            mPresenter.getMainMarketGoodsList();
        }
    }

    @Override
    public void onLoadMarketDataFailed() {
        mRefreshLayout.finishRefresh();
        //显示网络异常缺省页
        mAdapter.isUseEmpty(true);
    }

    @Override
    public void onLoadGoodsSuccess(MallGoodsBean mallGoodsBean) {
        if (mallGoodsBean != null && mallGoodsBean.getList() != null && mallGoodsBean.getList().size() != 0) {
            mMallListBeanList.add(new MallListBean());//分割线
            mAdapter.addData(mallGoodsBean);
        } else {
            mRefreshLayout.finishLoadMoreWithNoMoreData();
        }
        mRefreshLayout.finishLoadMore();
    }

    @Override
    public void onLoadMarketGoodsDataFailed() {
        mRefreshLayout.finishLoadMore();
    }

    /**
     * 分页商品加载更多数据
     *
     * @param mallGoodsBean
     */
    @Override
    public void onLoadGoodsMoreSuccess(MallGoodsBean mallGoodsBean) {
        mRefreshLayout.finishLoadMore();
        if (mallGoodsBean != null && mallGoodsBean.getList() != null && mallGoodsBean.getList().size() != 0) {
            mAdapter.addData(mallGoodsBean);
        } else {
            mRefreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void onLoadMarketGoodsMoreDataFailed() {
        mRefreshLayout.finishLoadMore();
    }

    @Override
    public void onLoadSuccess(MyPersonalBean myPersonalBean) {
        if (myPersonalBean != null) {
            Hawk.put(SPKey.SP_KEY_USER_MY_INFO, myPersonalBean);
        }
    }

    @Override
    public void onLoadPersonalDataFailed() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @OnClick({R.id.home_iv_cart, R.id.search_layout_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home_iv_cart:
                Intent intent = new Intent(mContext, CartActivity.class);
                startActivity(intent);
                break;
            case R.id.search_layout_right:
                intent = new Intent(mContext, MessageTabActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 读取本地保存的搜索历史记录关键字
     *
     * @return
     */
    private List<String> getHisSearchTags() {
        String search = Hawk.get("search", null);
        if (TextUtils.isEmpty(search)) {
            return null;
        }
        List<String> keys = JSON.parseArray(search, String.class);
        return keys;
    }
}
